<template>
  <div>
    <el-upload
      action="#"
      ref="upload"
      :file-list="fileData"
      :on-change="beforeUpload"
      :class="{hide:hideUploadEdit}"
      list-type="picture-card"
      multiple
      drag
      :limit="limit"
      accept=".jpg,.jpeg,.gif,.png,.bmp,.mp4,.mov,.avi,.mp3,.ogg,.rmvb,.mkv,"
      :auto-upload="false">
      <i class="el-icon-upload"></i>
      <div style="position: absolute;top: 44px;width: 100%;">将文件拖到此处，或<em>点击上传</em></div>
      <div slot="file" slot-scope="{file}" style="width: 148px;height: 148px;display: table-cell;vertical-align: middle;text-align: center">
        <img
          v-if="creativeType(file) === 'image'"
          class="el-upload-list__item-thumbnail"
          style="max-height: 100%;max-width: 100%;height: auto;width: auto"
          :src="file.url" alt=""
        >
        <video v-if="creativeType(file)  === 'video'" style="max-height: 100%;max-width: 100%;height: auto;width: auto"
               class="el-upload-list__item-thumbnail" :src="file.url">

        </video>
        <span class="el-upload-list__item-actions">
        <span
          class="el-upload-list__item-preview"
          @click="handlePictureCardPreview(file)"
        >
          <i class="el-icon-zoom-in"></i>
        </span>
          <span v-if="creativeType(file)  === 'video'" class="el-upload-list__item-preview">
             <i class="el-icon-video-camera"></i>
          </span>
            <span v-if="creativeType(file)  === 'image'" class="el-upload-list__item-preview">
             <i class="el-icon-picture-outline"></i>
          </span>
        <span
          v-if="!disabled"
          class="el-upload-list__item-delete"
          @click="handleRemove(file)"
        >
          <i class="el-icon-delete"></i>
        </span>
      </span>
      </div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" :modal-append-to-body="false" top="0px;"
               :close-on-click-modal="false" :before-close="handleClose" :append-to-body="true" width="80%">
      <img v-if="dialogType === 'image'" :style="previewStyle()" :src="dialogImageUrl">
      <video v-if="dialogType === 'video'" :src="dialogImageUrl" :style="previewStyle()" controls="controls"></video>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: 'beetlesUpload',
  props: {
    fileList: {
      type: Array,
    },
    limit: {
      type: String
    }
  },
  data() {
    return {
      dialogType: '',
      dialogImageUrl: '',//dialog内的文件
      dialogVisible: false,
      disabled: false,
      // fileList:[],//素材列表
      fileData: [],
      hideUploadEdit: false
    }
  },
  watch: {
    fileList: {
      deep: true,
      handler(val,old) {
        if(val === old){
          return
        }
        this.hideUploadEdit = this.fileList >= this.limit
       this.fileData = this.fileList
        this.fileData.map(item =>{
          item.url = item.url + '?' + new Date().getTime();
        })
      }
    },
  },
  methods: {
    previewStyle() {
      let height = ((window.innerHeight < 300)?300:(window.innerHeight - 160));
      return {
        maxWidth: '100%',
        maxHeight: height + 'px'
      };
    },
    beforeUpload(file, fileList) {
      if(fileList.length > this.limit) {
        this.postMessage("上传的文件数量一次性不可超过" + this.limit + "个!","warning");
        this.remove(file)
        return false;
      }
      const extension = ["image","video"].includes(this.creativeType(file));
      if (!extension) {
        this.postMessage("上传的文件格式只能是.jpg , .png , .mp4 , .mp3 , .jpeg!","warning");
        this.remove(file);
        return false;
      } else if (file.size > 100 * 1024 * 1024) {
        this.postMessage("上传的单个文件不能超过100M!","warning");
        this.remove(file)
        return false;
      } else {
        let totalSize = 0;
        fileList.forEach((f)=>{
          totalSize += f.size;
        });
        if(totalSize > 500 * 1024 * 1024) {
          this.postMessage("上传的所有文件不能超过500M!","warning");
          this.remove(file)
          return false;
        }
      }
      this.hideUploadEdit = fileList.length >= this.limit;
      return true;
    },
    postMessage(msg,type) {
      let self = this;
      if(self.postSingleMessageDisable) {
        return;
      }
      self.postSingleMessageDisable = true;
      self.$message({
        message: msg,
        type: type,
        onClose: ()=>{
          self.postSingleMessageDisable = false;
        }
      });
    },
    //删除素材
    handleRemove(file) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let fileList = this.$refs.upload.uploadFiles;
        let index = fileList.findIndex((fileItem) => {
          return fileItem.uid === file.uid;
        });
        // this.fileData.splice(index, 1);
        fileList.splice(index, 1);
        this.fileData = fileList
        this.hideUploadEdit = fileList.length >= this.limit
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
        return
      });
    },
    remove(file){
      let fileList = this.$refs.upload.uploadFiles;
      let index = fileList.findIndex((fileItem) => {
        return fileItem.uid === file.uid;
      });
      // this.fileData.splice(index, 1);
      fileList.splice(index, 1);
      this.fileData = fileList
      this.hideUploadEdit = fileList.length >= this.limit
      this.$message({
        type: 'success',
        message: '删除成功!'
      });
    },
    //素材放大
    handlePictureCardPreview(file) {
      if (this.creativeType(file) === 'image') {
        this.dialogType = 'image'
      } else if (this.creativeType(file) === 'video') {
        this.dialogType = 'video'
      }
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //关闭放大弹窗
    handleClose() {
      this.dialogVisible = false
    },
    creativeType(file) {
      let type = '';
      let url = file.url;
      if(url != null) {
        url = url.split('?')[0];
      }
      let name = file.name;
      if(name != null) {
        name = name.split('?')[0];
      }

      let urlTail = ((url != null && url.indexOf('.') >= 0) ? (url.substring(url.lastIndexOf('.') + 1)) : '').toLowerCase();
      let nameTail = ((name != null && name.indexOf('.') >= 0) ? (name.substring(name.lastIndexOf('.') + 1)) : '').toLowerCase();

      let imgList = ['jpg', 'jpeg', 'png', 'gif', 'bmp']
      let videoList = ['mp4', 'mov', 'avi', 'mp3', 'ogg', 'rmvb', 'mkv']
      if (imgList.includes(urlTail) || imgList.includes(nameTail)) {
        type = 'image'
      } else if (videoList.includes(urlTail) || videoList.includes(nameTail)) {
        type = 'video'
      }
      return type
    }
  }
}
</script>
<style lang="scss">
// 隐藏上传按钮
.hide .el-upload--picture-card {
  display: none;
}

// 添加/删除文件时去掉动画过渡
.el-upload-list__item {
  transition: none !important;
}
.el-upload-list--picture-card{
  display: block;
}
</style>
